package com.yijiu.trb;

import java.util.Calendar;

import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.yijiu.action.BaseAction;
import com.yijiu.adapter.InvestRecordAdapter;
import com.yijiu.adapter.MoneyInOutAdapter;
import com.yijiu.adapter.ScrollFootListener;
import com.yijiu.network.Request;
import com.yijiu.resource.ActionType;
import com.yijiu.resource.C;
import com.yijiu.resource.CacheData;
import com.yijiu.response.InvestRecordResponse;
import com.yijiu.response.MoneyInResponse;
import com.yijiu.response.MoneyOutResponse;

/**
 * 我的记录
 * 
 * @author TangChao_Lenovo
 */
public class MyRecordActivity extends BTitleWithUserinfoActivity implements ScrollFootListener
{
	/**
	 * 记录列表
	 */
	private ListView recordListView;
	
	/**
	 * 投资记录适配器
	 */
	private InvestRecordAdapter investRecordAdapter;
	
	/**
	 * 划入划出适配器
	 */
	private MoneyInOutAdapter moneyInOutAdapter;
	
	private LinearLayout llayoutInvestInfo;
	
	private TextView investAll;
	
	private int pageIndex = 1;
	
	private boolean isLoadOver = false, onFoot = false;
	
	private String type = "invest";
	
	private long exitTime = 0;
	
	private boolean isRequest = false;
	
	public static MyRecordActivity instance = null;
	
	private OnCheckedChangeListener investInOutListener = new OnCheckedChangeListener()
	{
		@Override
		public void onCheckedChanged(RadioGroup group, int checkID)
		{
			pageIndex = 1;
			onFoot = false;
			isLoadOver = false;
			isRequest = false;
			if (investRecordAdapter != null)
			{
				investRecordAdapter.clear();
			}
			if (moneyInOutAdapter != null)
			{
				moneyInOutAdapter.clear();
			}
			switch (checkID)
			{
				case R.id.rb_invest_record_invest:// 投资记录按钮
					type = "invest";
					llayoutInvestInfo.setVisibility(View.VISIBLE);
					requestInvestRecordList(pageIndex, onFoot);
					break;
				case R.id.rb_invest_record_in:// 划入记录按钮
					type = "in";
					llayoutInvestInfo.setVisibility(View.GONE);
					requestMoneyInList(pageIndex, onFoot);
					break;
				case R.id.rb_invest_record_out:// 划出记录按钮
					type = "out";
					llayoutInvestInfo.setVisibility(View.GONE);
					requestMoneyOutList(pageIndex, onFoot);
					break;
				default:
					break;
			}
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_investment_record_layout);
		initWidget();
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		refresh();
	}
	
	@Override
	protected void initWidget()
	{
		instance = this;
		llayoutInvestInfo = (LinearLayout) findViewById(R.id.llayout_invest_info);
		investAll = (TextView) findViewById(R.id.tv_invest_record_all);
		recordListView = (ListView) findViewById(R.id.lv_invest_record);
		RadioGroup rgInvestInOut = (RadioGroup) findViewById(R.id.rg_invest_record);
		RadioButton rbInvest = (RadioButton) findViewById(R.id.rb_invest_record_invest);
		RadioButton rbIn = (RadioButton) findViewById(R.id.rb_invest_record_in);
		RadioButton rbOut = (RadioButton) findViewById(R.id.rb_invest_record_out);
		rgInvestInOut.setOnCheckedChangeListener(investInOutListener);
		if (CacheData.ROLE.equals("12"))
		{
			requestInvestRecordList(pageIndex, onFoot);
		}
		else
		{
			rbInvest.setVisibility(View.GONE);
			rbIn.setChecked(true);
			type = "in";
			llayoutInvestInfo.setVisibility(View.GONE);
			requestMoneyInList(pageIndex, onFoot);
		}
	}
	
	private String get3MonthBefor()
	{
		int year, month, day;
		String monthStr, dayStr;
		Calendar cur = Calendar.getInstance();
		year = cur.get(Calendar.YEAR);
		month = cur.get(Calendar.MONTH) + 1;
		day = cur.get(Calendar.DAY_OF_MONTH) + 1;
		switch (month)
		{
			case 1:
			case 2:
			case 3:
				month += 9;
				year--;
				break;
			default:
				month -= 3;
				break;
		}
		monthStr = (month < 10) ? ("0" + month) : ("" + month);
		dayStr = (day < 10) ? ("0" + day) : ("" + day);
		return year + "-" + monthStr + "-" + dayStr;
	}
	
	private String getNowDate(boolean isAddOne)
	{
		int year, month, day;
		String monthStr, dayStr;
		Calendar cur = Calendar.getInstance();
		if (isAddOne)
			cur.add(Calendar.DAY_OF_MONTH, 1);
		year = cur.get(Calendar.YEAR);
		month = cur.get(Calendar.MONTH) + 1;
		day = cur.get(Calendar.DAY_OF_MONTH);
		monthStr = (month < 10) ? ("0" + month) : ("" + month);
		dayStr = (day < 10) ? ("0" + day) : ("" + day);
		return year + "-" + monthStr + "-" + dayStr;
	}
	
	/**
	 * 请求投资记录列表
	 */
	private void requestInvestRecordList(int pageIndex, boolean onFoot)
	{
		isRequest = false;
		// 将用户输入的信息拼接成字符串发送到服务器
		// String inputStr = "service=inverstRecordService&startDate=" + get3MonthBefor() + "&endDate=" +
		// getNowDate(true)
		// + "&pageSize=10&pageNo=" + pageIndex;
		String inputStr = "service=inverstRecordService&startDate=" + "&endDate=" + getNowDate(true)
				+ "&pageSize=10&pageNo=" + pageIndex;
		// 用私钥进行AES加密
		encryptBase(inputStr, C.PRIVATE_KEY);
		// 将用公钥加密后的私钥、用私钥加密后的数据进行封装
		BaseAction requestData = new BaseAction(encodedData, encriptData, CacheData.APP_KEY);
		// 登录响应
		InvestRecordResponse investRecordResponse = new InvestRecordResponse();
		// 请求服务器
		Request request = new Request(requestData, investRecordResponse, ActionType.INVEST_RECORD);
		netManager.excute(request, this, this);
		if (onFoot)
		{
			investRecordAdapter.showprogress();
		}
		else
		{
			showProgress("正在获取投资记录数据，请稍候");
		}
	}
	
	/**
	 * 请求划入记录列表
	 */
	private void requestMoneyInList(int pageIndex, boolean onFoot)
	{
		isRequest = false;
		// 将用户输入的信息拼接成字符串发送到服务器
		String inputStr = "service=deductRecordService&startDate=" + get3MonthBefor() + "&endDate=" + getNowDate(true)
				+ "&pageSize=10&pageNo=" + pageIndex;
		// 用私钥进行AES加密
		encryptBase(inputStr, C.PRIVATE_KEY);
		// 将用公钥加密后的私钥、用私钥加密后的数据进行封装
		BaseAction requestData = new BaseAction(encodedData, encriptData, CacheData.APP_KEY);
		// 登录响应
		MoneyInResponse moneyInResponse = new MoneyInResponse();
		// 请求服务器
		Request request = new Request(requestData, moneyInResponse, ActionType.MONEY_IN);
		netManager.excute(request, this, this);
		if (onFoot)
		{
			moneyInOutAdapter.showprogress();
		}
		else
		{
			showProgress("正在获取划入记录数据，请稍候");
		}
	}
	
	/**
	 * 请求划出记录列表
	 */
	private void requestMoneyOutList(int pageIndex, boolean onFoot)
	{
		// 将用户输入的信息拼接成字符串发送到服务器
		isRequest = false;
		String inputStr = "service=withdrawasRecordService&startDate=" + get3MonthBefor() + "&endDate=" + getNowDate(false)
				+ "&pageSize=10&pageNo=" + pageIndex;
		Log.e("result1", inputStr);
		// 用私钥进行AES加密
		encryptBase(inputStr, C.PRIVATE_KEY);
		// 将用公钥加密后的私钥、用私钥加密后的数据进行封装
		BaseAction requestData = new BaseAction(encodedData, encriptData, CacheData.APP_KEY);
		// 登录响应
		MoneyOutResponse moneyOutResponse = new MoneyOutResponse();
		// 请求服务器
		Request request = new Request(requestData, moneyOutResponse, ActionType.MONEY_OUT);
		netManager.excute(request, this, this);
		if (onFoot)
		{
			moneyInOutAdapter.showprogress();
		}
		else
		{
			showProgress("正在获取划出记录数据，请稍候");
		}
	}
	
	/* 操作成功返回的函数 */
	@Override
	public void getResult(Request r)
	{
		super.getResult(r);
		int type = r.getType();
		switch (type)
		{
			case ActionType.INVEST_RECORD:// 投资记录
				isRequest = true;
				if (onFoot)
				{
					investRecordAdapter.hideprogress();
				}
				InvestRecordResponse investRecordResponse = (InvestRecordResponse) r.getResponse();
				investAll.setText("￥" + investRecordResponse.investedTotalAmount);
				if (investRecordResponse.investRecordList == null || investRecordResponse.investRecordList.isEmpty()
						|| investRecordResponse.investRecordList.size() < 10)
				{
					isLoadOver = true;
				}
				else
				{
					isLoadOver = false;
				}
				if (investRecordAdapter == null || pageIndex == 1)
				{
					investRecordAdapter = new InvestRecordAdapter(this, investRecordResponse.investRecordList);
					investRecordAdapter.setScrollFootListener(this);
					recordListView.setAdapter(investRecordAdapter);
					recordListView.setEmptyView(findViewById(android.R.id.empty));
				}
				else
				{
					if (investRecordResponse.investRecordList != null && !investRecordResponse.investRecordList.isEmpty())
					{
						investRecordAdapter.addAll(investRecordResponse.investRecordList);
					}
				}
				setTitleInfoVisibility();
				refresh();
				break;
			case ActionType.MONEY_IN:// 划入记录
				isRequest = true;
				if (onFoot)
				{
					moneyInOutAdapter.hideprogress();
				}
				MoneyInResponse moneyInResponse = (MoneyInResponse) r.getResponse();
				if (moneyInResponse.moneyInList == null || moneyInResponse.moneyInList.isEmpty()
						|| moneyInResponse.moneyInList.size() < 10)
				{
					isLoadOver = true;
				}
				else
				{
					isLoadOver = false;
				}
				if (moneyInOutAdapter == null || pageIndex == 1)
				{
					moneyInOutAdapter = new MoneyInOutAdapter(this, false, moneyInResponse.moneyInList);
					moneyInOutAdapter.setScrollFootListener(this);
					recordListView.setAdapter(moneyInOutAdapter);
					recordListView.setEmptyView(findViewById(android.R.id.empty));
				}
				else
				{
					if (moneyInResponse.moneyInList != null && !moneyInResponse.moneyInList.isEmpty())
					{
						moneyInOutAdapter.addAll(moneyInResponse.moneyInList);
					}
				}
				setTitleInfoVisibility();
				refresh();
				break;
			case ActionType.MONEY_OUT:// 划出记录
				isRequest = true;
				if (onFoot)
				{
					moneyInOutAdapter.hideprogress();
				}
				MoneyOutResponse moneyOutResponse = (MoneyOutResponse) r.getResponse();
				Log.e("result1", "=============" + moneyOutResponse.moneyOutList.size());
				if (moneyOutResponse.moneyOutList == null || moneyOutResponse.moneyOutList.isEmpty()
						|| moneyOutResponse.moneyOutList.size() < 10)
				{
					isLoadOver = true;
				}
				else
				{
					isLoadOver = false;
				}
				if (moneyInOutAdapter == null || pageIndex == 1)
				{
					moneyInOutAdapter = new MoneyInOutAdapter(this, true, moneyOutResponse.moneyOutList);
					moneyInOutAdapter.setScrollFootListener(this);
					recordListView.setAdapter(moneyInOutAdapter);
					recordListView.setEmptyView(findViewById(android.R.id.empty));
				}
				else
				{
					if (moneyOutResponse.moneyOutList != null && !moneyOutResponse.moneyOutList.isEmpty())
					{
						moneyInOutAdapter.addAll(moneyOutResponse.moneyOutList);
					}
				}
				setTitleInfoVisibility();
				refresh();
				break;
		}
	}
	
	/* 操作失败返回的函数 */
	@Override
	public void notifyError(int type, int errorCode, String errorMsg)
	{
		super.notifyError(type, errorCode, errorMsg);
		switch (type)
		{
			case ActionType.INVEST_RECORD:
			case ActionType.MONEY_IN:
			case ActionType.MONEY_OUT:
				app.showMsg(errorMsg);
				recordListView.setEmptyView(findViewById(android.R.id.empty));
				if (errorCode == 2)
				{
					setTitleInfoVisibility();
				}
				else
				{
					setTitleInfoInVisibility();
				}
				break;
		}
	}
	
	/* 重复提交返回的函数 */
	@Override
	public void rePost(Request r)
	{
		super.rePost(r);
	}
	
	@Override
	public void onFoot()
	{
		if (isLoadOver)
		{
			return;
		}
		onFoot = true;
		if ("invest".equals(type) && isRequest)
		{
			requestInvestRecordList(++pageIndex, onFoot);
		}
		else if ("in".equals(type) && isRequest)
		{
			requestMoneyInList(++pageIndex, onFoot);
		}
		else if ("out".equals(type) && isRequest)
		{
			Log.e("result1", "-----------------" + pageIndex);
			requestMoneyOutList(++pageIndex, onFoot);
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN)
		{
			if ((System.currentTimeMillis() - exitTime) > 2000)
			{
				Toast.makeText(getApplicationContext(), "再按一次返回键退出程序", Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			}
			else
			{
				finish();
				System.exit(0);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
